import plugin from '../../../lib/plugins/plugin.js'
import fetch from 'node-fetch'

export class btSearch extends plugin {
  constructor() {
    super({
      name: '[碎月]搜磁力',
      dsc: '通过名称搜索磁力猫网站磁力链接',
      event: 'message',
      priority: 1000,
      rule: [
        {
          reg: '^#?搜磁力(.*)$',
          fnc: 'btsearch'
        }
      ]
    })
  }

  async btsearch() {
    try {
      let msg = this.e.msg.replace(/#|＃|搜磁力/g, "");

      let url = "https://xn--tfrs17es0d.com/"; //获取最新接口地址
      let response = await fetch(url);
      let res = await response.text(); //获取页面内容
      let urlnew = res.match(/<a href="(http[s]?:\/\/.*?)"/g);
      if (!urlnew || urlnew.length <= 0) {
        await this.reply("服务似乎开小差了，等会再试试吧。");
        return true;
      }

      urlnew = urlnew[Math.floor(Math.random() * urlnew.length)].replace(/<a href="|"|'/g, "");

      if (!msg || msg.length <= 0) {
        await this.reply("请输入需要搜索的内容 [#搜磁力xxx]");
        return true;
      }
      let btSearchurl = urlnew + `/search-${msg}-0-0-1.html`;
      let responseBt = await fetch(btSearchurl);
      let resBt = await responseBt.text(); //获取页面内容
      let magnetBt = resBt.match(/<a href="(magnet.*?)"/g);
      if (!magnetBt || magnetBt.length <= 0) {
        await this.reply("没有找到相关的磁力资源！");
        return true;
      }
      let title = resBt.replace(/[\r\n]/g, "").match(/<div class="title"(.*?)div>/g);
      if (title && title.length > 0) {
        title = title[0].replace(/<.*?>/g, "").replace(/\ +/g, "");
        if (title.match(/高潮|喷水|无码|流出|做爱|操|插入|裸体|自慰|下贱|下体|湿蒂|插|呻吟/g)) {
          title = "神秘标题过于神秘无法展示";
        }
      } else {
        title = "未知标题";
      }
      magnetBt = magnetBt[0].replace(/<a href="|"|'/g, "");
      await this.reply("[神秘标题]:\n" + title + "\n[神秘代码]:\n" + magnetBt);
    } catch (err) {
      await this.reply(`出现了一些神秘的错误`);
    }
  }
}
